module button_counter(
    input clk,           // 系统时钟输入
    input rst_n,         // 复位信号（低电平有效）
    input button,        // 按键输入（低电平有效）
    output reg [7:0] count // 8位计数器输出
);

    // 去抖电路寄存器
    reg [1:0] button_sync;      // 按键同步寄存器，防止亚稳态
    reg [15:0] debounce_counter; // 去抖计数器
    reg button_stable;          // 稳定的按键信号
    reg button_stable_prev;     // 上一周期稳定的按键信号
    
    // 去抖计时参数
    parameter DEBOUNCE_TIME = 16'd10000; 
    
    // 按键同步电路
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            button_sync <= 2'b11; 
        end else begin
            button_sync <= {button_sync[0], button}; 
        end
    end
    
    // 去抖电路（判断按键是否稳定）
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            debounce_counter <= 16'd0; 
            button_stable <= 1'b1;     
        end else begin
            if (button_sync[1] != button_stable) begin
                if (debounce_counter == DEBOUNCE_TIME - 1) begin
                    button_stable <= button_sync[1]; 
                    debounce_counter <= 16'd0;      
                end else begin
                    debounce_counter <= debounce_counter + 16'd1; 
                end
            end else begin
                debounce_counter <= 16'd0; 
            end
        end
    end
    
    // 按键按下的边缘检测（低电平有效）
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            button_stable_prev <= 1'b1; 
        end else begin
            button_stable_prev <= button_stable; 
        end
    end
    
    // 8位计数器
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            count <= 8'd0; 
        end else if (button_stable_prev && !button_stable) begin
            // 按键按下的下降沿触发计数器加1
            count <= count + 8'd1;
        end
    end

endmodule
